#include <iostream>
#include <sys/shm.h>
#include <thread>
#include "TestClass.h"
#include "SharedMemory.h"

using namespace std;

int main()
{
    shared_memory::SharedMemory<TestClass> sharedMemory("/home/sherlock");
    if (!sharedMemory.create(sizeof(TestClass), shared_memory::ReadWrite))
    {
        cout << "create share memory fail" << endl;
        if (sharedMemory.error() == shared_memory::AlreadyExists)
        {
            if (!sharedMemory.attach(shared_memory::ReadWrite))
            {
                cout << "attach fail" << endl;
                return -1;
            }
        }
    }
    cout << "create share memory pass" << endl;
    TestClass *data = sharedMemory.data();

    int index = 0;
    while (true)
    {
        data->setNum(index++);
        data->setData("asd");
        if (index >= 9999)
        {
            index = 0;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(5));
    }

    return 0;
}

//int main()
//{
//    int num = 333;
//    key_t key = ftok("/home", 0);
//    cout << key << endl;
//    int shmid = shmget(key, sizeof(TestClass), 0666 | IPC_CREAT);
//    void *shm = shmat(shmid, (void *) nullptr, 0);
//    TestClass *test = (TestClass *) shm;
//
//    while (true)
//    {
//        test->setNum(num);
//    }
//    shmdt(shm);
//    shmctl(shmid, IPC_RMID, nullptr);//删除共享内存
//    return 0;
//}
